import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by lenovo on 2018/10/31.
 */
public class ServiceDiscovery {
    List<String> serviceReps=new ArrayList<>();

    CuratorFramework curatorFramework=null;

    private final String REGISTER_ROOT="/register";

    {
        curatorFramework= CuratorFrameworkFactory.builder()
                .connectString("172.30.1.171:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(
                        new ExponentialBackoffRetry(1000,10)
                ).build();

        curatorFramework.start();
    }

    public void init(String serviceName) throws Exception {
        String path = REGISTER_ROOT + "/" + serviceName;

        try {
            serviceReps = curatorFramework.getChildren().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        registerWatcher(path);
    }

    private void registerWatcher(String path) throws Exception {
        PathChildrenCache pathChildrenCache=new PathChildrenCache(curatorFramework,path,true);
        PathChildrenCacheListener pathChildrenCacheListener=new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                serviceReps=curatorFramework.getChildren().forPath(path);
            }
        };

        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();
    }

    public String getServletEndPoint(){
        int length=serviceReps.size();
        if(length==1){
            return serviceReps.get(0);
        }
        Random random=new Random();
        return serviceReps.get(random.nextInt(length));
    }

    public static void main(String [] args) throws Exception {
        ServiceDiscovery serviceDiscovery=new ServiceDiscovery();
        serviceDiscovery.init("waiter");
        for(int i=0;i<10;i++){
            System.out.println(serviceDiscovery.getServletEndPoint());
            Thread.sleep(5000);
        }
    }
}
